//
//  ViewController.swift
//  DoubanRadioSwift
//
//  Created by shaneZhang on 15/5/3.
//  Copyright (c) 2015年 shaneZhang. All rights reserved.
//

import UIKit
import MediaPlayer

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,HttpControlDelegate,MusicListVCDelegate
{

    @IBOutlet weak var bgImageView: UIImageView!
    @IBOutlet weak var topBgImageView: ShaneImage!
    
    @IBOutlet weak var timeLabel: UILabel!
    
    @IBOutlet weak var smallImageView: ShaneImage!
    @IBOutlet weak var musicListTableView: UITableView!
    
    
    var httpRequest:HTTPController = HTTPController()
    
    var channelData:[JSON] = []
    
    var musicData:[JSON] = []
    
    
    var imageCache = Dictionary<String,UIImage>() // 图片换成的字典
    
    //申明一个媒体播放器的实例
    var audioPlayer:MPMoviePlayerController =  MPMoviePlayerController()
    
    //申明一个计时器
    var timer:NSTimer?
    
    //当前在播放第几首
    var currIndex:Int = 0
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        // 让图片弄成原型并且自动旋转
        topBgImageView.onRotation()
        
        // 模糊的效果
        let bluerEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
        let bluerView = UIVisualEffectView(effect: bluerEffect)
        bluerView.frame.size = CGSize(width: view.frame.width, height: view.frame.height)
        bgImageView.addSubview(bluerView)
        
        musicListTableView.delegate = self
        musicListTableView.dataSource = self
        musicListTableView.backgroundView = nil
        musicListTableView.backgroundColor = UIColor.clearColor()
        
        
        httpRequest.delegate = self
        httpRequest.onSearch("http://www.douban.com/j/app/radio/channels")
        httpRequest.onSearch("http://douban.fm/j/mine/playlist?type=n&channel=0&from=mainsite")
        
        
        //播放结束通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "playFinish", name: MPMoviePlayerPlaybackDidFinishNotification, object: audioPlayer)
        
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return self.musicData.count
    }
    
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("musicListCell") as! UITableViewCell
        
        // 获取tableView展示的数据
        let rowData:JSON = musicData[indexPath.row]
        
        cell.textLabel?.text = rowData["title"].string
        cell.detailTextLabel?.text = rowData["artist"].string
        cell.backgroundView = nil
        cell.backgroundColor = UIColor.clearColor()
        cell.contentView.backgroundColor = UIColor.clearColor()
        
        cell.imageView?.image = UIImage(named: "thumb")
        let url = rowData["picture"].string
        
        self.onGetCacheImage(url!, imageView: cell.imageView!)
        
        return cell
    
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        self.onSelectRow(indexPath)
    }
    
    func onSelectRow(index:NSIndexPath)
    {
        musicListTableView.selectRowAtIndexPath(index, animated: false, scrollPosition: UITableViewScrollPosition.Top)
        var rowData:JSON = self.musicData[index.row] as JSON
        let imgUrl = rowData["picture"].string
        
        onSetImage(imgUrl!)
        
        //获取音乐的文件地址
        var url:String = rowData["url"].string!
        //播放音乐
        onSetAudio(url)
    }
    
    
    //播放音乐的方法
    func onSetAudio(url:String)
    {
        self.audioPlayer.stop()
        self.audioPlayer.contentURL = NSURL(string: url)
        self.audioPlayer.play()
        
//        btnPlay.onPlay()
        
        //先停掉计时器
//        timer?.invalidate()
        //将计时器归零
        self.timeLabel.text = "00:00"
        
        //启动计时器
//        timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "onUpdate", userInfo: nil, repeats: true)
        
//        isAutoFinish = true
    }

    
    func playFinish()
    {
        
    }
    
    func onSetImage(url:String)
    {
        self.onGetCacheImage(url, imageView: self.topBgImageView)
        self.onGetCacheImage(url, imageView: self.bgImageView)
        self.onGetCacheImage(url, imageView: self.smallImageView)
    }

    
    func didRecieveNetworkingResults(results: AnyObject)
    {
        
        println("网络接收到的数据是:\(results)")
        let json = JSON(results)
        
        if let channels = json["channels"].array
        {
            self.channelData = channels
        }
        else if let song = json["song"].array
        {
            self.musicData = song
            
            musicListTableView.reloadData()
            
            let indexPath:NSIndexPath = NSIndexPath(forRow: 0, inSection: 0)
            onSelectRow(indexPath)
        }
    }
    
    func onChangeChannel(channel_Id: NSString)
    {
        let url:String = "http://douban.fm/j/mine/playlist?type=n&channel=\(channel_Id)&from=mainsite"
        
        httpRequest.onSearch(url)
    }
    
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
    {
        var channelVC:MusicListVC = segue.destinationViewController as! MusicListVC
        channelVC.delegate = self
        channelVC.channelData = self.channelData
    }

    
    
    func onGetCacheImage(url:String,imageView:UIImageView)
    {
        let image = self.imageCache[url as String] as UIImage?
        
        if  image == nil
        {
            //如果缓存中没有这张图片，就通过网络获取
            Alamofire.manager.request(Method.GET, url).response { (_, _, data, error) -> Void in
                //将图片数据赋予UIImage
                let img = UIImage(data: data! as! NSData)
                //设置封面的缩略图
                self.imageCache[url] = img
                imageView.image = img
            }
        }
        else
        {
            // 直接从缓存中取出来，设置就可以了
            imageView.image = image
        }
    }
}


